var actionPath='/system/role/';
var rootActionPath=parent.CONTEXT_PATH+actionPath;
var role = {
	getArr: function(obj, key, ar){
		$.each(obj, function(i, o){
			ar.push(o[key]);
			if(o.children){
				role.getArr(o.children, key, ar);
			}
		});
	},
	reTree: function(data){
		var lis = $('#menuTree li'), ar = [];
		role.getArr(data, 'attributes', ar);
		$.each(ar, function(i,o){
			if(o != "R"){
				lis.eq(i).find(".tree-checkbox:first").hide();
			}
		});
	}
};


jQuery(function($){
	var isFirst=true;
	$('#dg').datagrid({
		//角色选中事件
		onSelect : function(rowIndex, rowData){
			//如果选中的行是编辑的行就不执行（就是点修改后不触发这个操作）
			if(rowIndex == editingId){
				return;
			}
			if(rowData.id == undefined){
				return;
			}
			
			//如果已经有编辑的行
			if (editingId != undefined){
				$('#dg').datagrid('selectRow', editingId);
				return;
			}
			
			//显示系统菜单，并且有权限的勾上
			$('#menuTree').tree({
				url: rootActionPath+'queryPermissions.xhtml?isShowResource=true&roleIds='+rowData.id
			});
		},
		
		onCheck:function(rowIndex,rowData){
			//如果已经有编辑的行
			if (editingId != undefined && editingId != rowIndex){
				$('#dg').datagrid('checkRow', editingId);
				return;
			}
		},
		//加载成功选中第一行
		onLoadSuccess : function(data){
			roleData = data;
			if(isFirst){
				try{
					$('#dg').datagrid("checkRow",0);
				}catch(e){}
				
				isFirst = false;
			}
		},
		
		columns:[[
	  		{field:'ck',checkbox:true},//roleFieldName
	  		{field:'name',editor:'text',required:true,width:60,title:I18N.roleFieldName},
	  		{field:'description',editor:'text',width:120,title:I18N.roleFieldDescription,
	  			formatter: function(value,row,index){
	  				return '<span title="'+value+'">'+value+'</span>';
	  			}
	  		}
	  	]]
	});

	
	$('#menuTree').tree({
		//url:parent.CONTEXT_PATH+'/system/module/queryAll.xhtml?isBuilerResoures=true',
		checkbox : true,
		cascadeCheck:true,
		//onlyLeafCheck:true,
		lines:true,
		onCheck : function(node){
			$('#permissionsBut').linkbutton("enable");
		},
		//加载之前打开tips
		onBeforeLoad : function(node, param){
			$('#treeLoading').html(GLOBAL_I18N.global_progress_text).show(); 
			$('#tloadmask').show();
		},
		//加载成功禁用授权按钮
		onLoadSuccess : function(node, data){
			$('#permissionsBut').linkbutton("disable");
			role.reTree(data);
			$('#treeLoading, #tloadmask').hide();
		},
		onLoadError: function(arguments){
			$('#treeLoading, #tloadmask').hide();
		},
	});

});


var added = true;
var editingId =undefined;
var roleData;
function add() {

	//如果是编辑状态（editingId有值）
	if(editingId != undefined){
		return;
	}
	//如果是增加
	if(added){
		$('#dg').datagrid('insertRow',{
			index: 0,	// index start with 0
			row: {
				oa_role_name: '',
				oa_role_shuoming: ''
			}
		});
		$('#dg').datagrid('selectRow', 0);
		added = false;
		//选中行后调用编辑方法
		edit();
	}else{
		$('#dg').datagrid('selectRow', 0);
	}
	
}

	
function del(){
	var row = $('#dg').datagrid('getSelected');
	if(!row || !row.id){
		parent.showWarningBox(Audaque.format(GLOBAL_I18N.global_message_please_select_remove,I18N.moduleName)); 
		return;
	}
	
	if(row.name==GLOBAL_I18N.adminRoleName){
		parent.showWarningBox(I18N.systemRoleRemoveMsg); 
		return;
	}
	
	parent.showConfirmBox(Audaque.format(GLOBAL_I18N.global_message_remove_ask,I18N.moduleName), function(bool) {
		if (bool) {	
			parent.postReturnJson
			(
				actionPath+'remove.xhtml',
				{id : row.id},
				function(result){
					if (result.success) {
						$('#dg').datagrid('reload');
						$('#dg').datagrid('clearSelections');
					}
				}
			);
		}
	});
}


function edit(){
	if (editingId != undefined){
		$('#dg').datagrid('selectRow', editingId);
		return;
	}
	var row = $('#dg').datagrid('getSelected');
	if(row.name==GLOBAL_I18N.adminRoleName){
		parent.showWarningBox(I18N.systemRoleUpdateMsg); 
		return;
	}
	if (row){
		var rowIndex = $('#dg').datagrid('getRowIndex', row);
		if(rowIndex == -1){
			parent.showWarningBox(Audaque.format(GLOBAL_I18N.global_message_please_select_edit,I18N.moduleName));
			return;
		}
		$('#dg').datagrid('beginEdit', rowIndex); 
		editingId = rowIndex;
		$('#saveBut').linkbutton("enable");
		$('#cancelBut').linkbutton("enable");
	}else{
		parent.showWarningBox(Audaque.format(GLOBAL_I18N.global_message_please_select_edit,I18N.moduleName));
	}
}


function save(){
	
	//如果已经增加那么就是修改
	if(added){
		if (editingId != undefined){
			addOrUpdate('update.xhtml',true);
		}
	}else {
		$('#dg').datagrid('selectRow', 0);
		addOrUpdate('create.xhtml',false);
	}
	
	//禁用授权按钮
	$('#permissionsBut').linkbutton("disable");
}


function addOrUpdate(uri,isUpdate){
	var t = $('#dg');
	t.datagrid('endEdit', editingId);
	var row = t.datagrid('getSelected');
	if(!row.name.trim()){
		t.datagrid('beginEdit', editingId); 
		parent.showWarningBox(Audaque.format(I18N.notNullError,I18N.roleFieldName));
		return;
	}else if(row.name.length > 50){
		t.datagrid('beginEdit', editingId); 
		parent.showWarningBox(Audaque.format(I18N.invalidLengthError,[I18N.roleFieldName,50]));
		return;
	}
	
	if(row.description.length > 240){
		t.datagrid('beginEdit', editingId); 
		parent.showWarningBox(Audaque.format(I18N.invalidLengthError,[I18N.roleFieldDescription,240]));
		return;
	}
	
	
	var roles= roleData.rows;
	for(var i=0;i<roles.length;i++){
		var role = roles[i];
		//alert(role.name +"\t"+ row.name);
		if(role.id && role.name.trim() == row.name.trim()){
			//如果是修改，自己和自己比的不算
			if(isUpdate && role.id == row.id){
				continue;
			}
			t.datagrid('beginEdit', editingId); 
			parent.showWarningBox(I18N.existingError);
			return;
		}
	}

	parent.postReturnJson
	(
		actionPath+uri,
		{
			id : row.id,
			name : row.name.trim(),
			description : row.description.trim(),
			statusCode : 0
		}, 
		function(result){
			editingId = undefined;
			$('#saveBut').linkbutton("disable");
			$('#cancelBut').linkbutton("disable");
			t.datagrid('reload');
			added = true;
		}
	);
}


function cancel(){
	
	if (editingId != undefined){
		$('#dg').datagrid('cancelEdit', editingId);
		editingId = undefined;
		$('#saveBut').linkbutton("disable");
		$('#cancelBut').linkbutton("disable");
	}
	
	if(!added){
		$('#saveBut').linkbutton("disable");
		$('#cancelBut').linkbutton("disable");
		added = true;
		$('#dg').datagrid('deleteRow',0);
	}
}


function collapse(){
	//var node = $('#menuTree').tree('getSelected');
	$('#menuTree').tree('collapseAll');
}
function expand(){
	//var node = $('#menuTree').tree('getSelected');
	$('#menuTree').tree('expandAll');
	//$('#menuTree').tree({cascadeCheck:true});
}

function cascade(){
	$('#menuTree').tree({cascadeCheck:true});
}
function selectAll(){
	$('#menuTree').tree("check",
	$('#menuTree').tree("getRoot").target);
}
//授权
function setPermissions(){

	var t = $('#dg');
	var row = t.datagrid('getSelected');
	if(!row){
		parent.showWarningBox(I18N.selectAuthorizationRole);
		return;
	}
	if (editingId != undefined){
		parent.showWarningBox(I18N.afterSave); 
		return;
	}
	
	if(row.name==GLOBAL_I18N.adminRoleName){
		parent.showWarningBox(I18N.systemRoleAuthorizationMsg); 
		return;
	}
	
	var resourceIds=[];
	var nodes = $('#menuTree').tree("getChecked");
	var len = nodes.length;
	for(var i=0;i<len;i++){
		var node = nodes[i];
		if(node.attributes === 'R'){
			resourceIds.push("resourceIds="+node.id);
		}
	}

	parent.postReturnJson
	(
		actionPath+'assignResources.xhtml?'+resourceIds.join('&'),
		{
			roleId : row.id
		}, 
		function(result){
			//禁用授权按钮
			$('#permissionsBut').linkbutton("disable");
		}
	);
}